package com.zkyc.framework.webgateway.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zkyc.framework.common.constant.Constant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.pojo.User;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.webgateway.config.JedisPoolFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;


@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 不验证accessToken的请求
     */
    private static final HashSet<String> PASSURL = new HashSet<>();

    static {
        PASSURL.add("login");
        PASSURL.add("list");
        PASSURL.add("/imgCode");
        PASSURL.add("search");
        PASSURL.add("List");
        PASSURL.add("query");
        PASSURL.add("insertViews");
        PASSURL.add("website/post/save");
        PASSURL.add("pi/getOrganization");
        PASSURL.add("/post/getHeader");
        PASSURL.add("previousNext");
        PASSURL.add("association/silhouetteById");
        PASSURL.add("/association/silhouette");
        PASSURL.add("activity/clickCount");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String url = request.getURI().getPath();
        log.info("url:{}",url);
        //3.获取当前用户的请求头token信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("accessToken");
        //若token没传
        if (StringUtils.isBlank(token)) {
            //2.判断当前的请求是否为登录，如果是，直接放行
            if (pass(url)) return chain.filter(exchange);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            ResultVO<Object> fail = ResultVO.fail("缺少accessToken");
            byte[] bytes = JSONObject.toJSONString(fail).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }
        String redisKey = Constant.REDIS_PREFIX + "TOKEN_" + token;
        String data = JedisPoolFactory.select(redisKey);

        //4.判断当前令牌是否存在
        if (data == null) {
            //如果不存在，向客户端返回错误提示信息
            //      response.setStatusCode(HttpStatus.UNAUTHORIZED);
            ResultVO<Object> fail = ResultVO.fail(ResultCode.UNAUTHORIZED);
            byte[] bytes = JSONObject.toJSONString(fail).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }
        //5.将用户id放入请求头中
        User user = JSON.parseObject(data, User.class);
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders ->
                httpHeaders.add("userId", user.getId())).build();
        exchange.mutate().request(serverHttpRequest).build();
        //6.放行
        return chain.filter(exchange);
    }

    private boolean pass(String url) {
        return PASSURL.stream().anyMatch(url::contains);
    }

    /**
     * 优先级设置
     * 值越小，优先级越高
     *
     * @return 0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}